package com.ruoyi.system.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import java.math.BigDecimal;
import java.util.List;
import java.util.Arrays;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.node.NumericNode;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.MedPre;
import com.ruoyi.system.domain.Medicine;
import com.ruoyi.system.service.IMedPreService;
import com.ruoyi.system.service.IMedicineService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Prescription;
import com.ruoyi.system.service.IPrescriptionService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 处方管理Controller
 *
 * @author yangxp
 * @date 2020-07-31
 */
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/medicine/prescription")
public class PrescriptionController extends BaseController {

	private final IPrescriptionService iPrescriptionService;
	private final IMedicineService iMedicineService;
	private final IMedPreService medPreService;
	/**
	 * 查询处方管理列表
	 */
	@PreAuthorize("@ss.hasPermi('medicine:prescription:list')")
	@GetMapping("/list")
	public TableDataInfo list(Prescription prescription) {
		startPage();
		LambdaQueryWrapper<Prescription> lqw = new LambdaQueryWrapper<Prescription>();
		if (StringUtils.isNotBlank(prescription.getPreName())) {
			lqw.like(Prescription::getPreName, prescription.getPreName());
		}
		List<Prescription> list = iPrescriptionService.list(lqw);

		list.forEach(item->{
			String preId = item.getPreId();
			List<MedPre> medicineList = medPreService.list(new QueryWrapper<MedPre>().eq("pre_id", preId));
			item.setMedicineList(medicineList);
		});

		return getDataTable(list);
	}

	/**
	 * 导出处方管理列表
	 */
	@PreAuthorize("@ss.hasPermi('medicine:prescription:export')")
	@Log(title = "处方管理", businessType = BusinessType.EXPORT)
	@GetMapping("/export")
	public AjaxResult export(Prescription prescription) {
		LambdaQueryWrapper<Prescription> lqw = new LambdaQueryWrapper<Prescription>(prescription);
		List<Prescription> list = iPrescriptionService.list(lqw);
		ExcelUtil<Prescription> util = new ExcelUtil<Prescription>(Prescription.class);
		return util.exportExcel(list, "prescription");
	}

	/**
	 * 获取处方详细信息
	 */
	@PreAuthorize("@ss.hasPermi('medicine:prescription:query')")
	@GetMapping(value = "/{id}")
	public AjaxResult getInfo(@PathVariable("id") String preId) {

		Prescription prescription = iPrescriptionService.getOne(new LambdaQueryWrapper<Prescription>().eq(Prescription::getPreId, preId));
		List<MedPre> medicineList = medPreService.list(new QueryWrapper<MedPre>().eq("pre_id", preId));
		prescription.setMedicineList(medicineList);
		return AjaxResult.success(prescription);
	}

	/**
	 * 新增处方管理
	 */
	@PreAuthorize("@ss.hasPermi('medicine:prescription:add')")
	@Log(title = "处方管理", businessType = BusinessType.INSERT)
	@PostMapping
	public AjaxResult add(@RequestBody Prescription prescription) {
		List<MedPre> medicineList = prescription.getMedicineList();
		BigDecimal totalPrice = getTotalPrice(medicineList,prescription.getAmount());
		prescription.setPrePrice(totalPrice);
		return toAjax(iPrescriptionService.savePrescription(prescription) ? 1 : 0);
	}

	/**
	 * 修改处方管理
	 */
	@PreAuthorize("@ss.hasPermi('medicine:prescription:edit')")
	@Log(title = "处方管理", businessType = BusinessType.UPDATE)
	@PutMapping
	public AjaxResult edit(@RequestBody Prescription prescription) {

		List<MedPre> medicineList = prescription.getMedicineList();
		prescription.setPrePrice(getTotalPrice(medicineList,prescription.getAmount()));
		return toAjax(iPrescriptionService.updatePrescription(prescription) ? 1 : 0);
	}

	/**
	 * 删除处方管理
	 */
	@PreAuthorize("@ss.hasPermi('medicine:prescription:remove')")
	@Log(title = "处方管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
	public AjaxResult remove(@PathVariable Long[] ids) {

		return toAjax(iPrescriptionService.removePrescription(ids) ? 1 : 0);
	}

	/**
	 * 计算药方金额
	 * @param prescription
	 * @return
	 */
	@PostMapping("/computePrice")
	public AjaxResult getSumMedicinePrice(@RequestBody Prescription prescription) {
		List<MedPre> medicineList = prescription.getMedicineList();
		BigDecimal price = getTotalPrice(medicineList,prescription.getAmount());
		String formatPrice = NumberUtil.decimalFormat("#.##", price.doubleValue());
		return AjaxResult.success("获取成功",formatPrice);
	}

	/**
	 * 根基药品列表计算总价
	 * @param medicineList
	 * @return
	 */
	private BigDecimal getTotalPrice(List<MedPre> medicineList,int amout){
		BigDecimal price = new BigDecimal(0);
		for (MedPre item : medicineList) {
			//克数
			BigDecimal gram = item.getMedGram();
			LambdaQueryWrapper<Medicine> lqw = new LambdaQueryWrapper<>();
			Medicine medicine = iMedicineService.getOne(lqw.eq(Medicine::getMedId, item.getMedId()));
			//获取售价
			BigDecimal marketPrice = medicine.getMarketPrice();
			//获取每个售价
			BigDecimal one = NumberUtil.mul(marketPrice, gram);
			//获取总价
			price = NumberUtil.add(price,one);
		}
		return NumberUtil.mul(price,amout);
	}

}
